package org.codefinger.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.codefinger.dao.util.jdbc.JDBCUtil;
import org.codefinger.dao.util.magic.MagicAttribute;
import org.codefinger.dao.util.magic.MagicPojo;

public class PojoBuilder<T> {

	private ResultSet			resultSet;

	private MagicAttribute[]	magicAttributes;

	private MagicPojo<T>		magicPojo;

	public PojoBuilder(ResultSet resultSet, String[] names, Class<T> clas) {
		super();
		this.resultSet = resultSet;
		MagicPojo<T> magicPojo = MagicPojo.getMagicPojo(clas);
		int length = names.length;
		MagicAttribute[] magicAttributes = new MagicAttribute[length];
		for (int i = 0; i < length;) {
			magicAttributes[i] = magicPojo.getMagicAttribute(names[i++]);
		}
		this.magicPojo = magicPojo;
		this.magicAttributes = magicAttributes;
	}

	public T nextPojo() throws SQLException {
		T object = magicPojo.newInstance();
		int length = magicAttributes.length;
		ResultSet resultSet = this.resultSet;
		MagicAttribute[] magicAttributes = this.magicAttributes;
		MagicAttribute attribute;
		Object value;
		for (int i = 0; i < length;) {
			attribute = magicAttributes[i++];
			if (attribute == null) {
				continue;
			}
			value = JDBCUtil.getResult(//
					resultSet, i, attribute.getField().getType());
			if (value == null) {
				continue;
			}
			attribute.setValue(object, value);
		}
		return object;
	}

}
